"""
存储系统统计和日志功能
"""

import time
from typing import Dict, List
from dataclasses import dataclass, field
from datetime import datetime


@dataclass
class CacheStats:
    """缓存统计信息"""
    cache_hits: int = 0
    cache_misses: int = 0
    total_requests: int = 0
    cache_size: int = 0
    max_cache_size: int = 0
    replacement_count: int = 0
    
    @property
    def hit_rate(self) -> float:
        """缓存命中率"""
        if self.total_requests == 0:
            return 0.0
        return self.cache_hits / self.total_requests
    
    @property
    def miss_rate(self) -> float:
        """缓存失效率"""
        return 1.0 - self.hit_rate
    
    def record_hit(self):
        """记录缓存命中"""
        self.cache_hits += 1
        self.total_requests += 1
    
    def record_miss(self):
        """记录缓存失效"""
        self.cache_misses += 1
        self.total_requests += 1
    
    def record_replacement(self):
        """记录页替换"""
        self.replacement_count += 1
    
    def __str__(self) -> str:
        return (f"CacheStats(hits={self.cache_hits}, misses={self.cache_misses}, "
                f"hit_rate={self.hit_rate:.2%}, replacements={self.replacement_count})")


@dataclass
class StorageStats:
    """存储系统统计信息"""
    pages_allocated: int = 0
    pages_deallocated: int = 0
    pages_read: int = 0
    pages_written: int = 0
    disk_reads: int = 0
    disk_writes: int = 0
    total_pages: int = 0
    free_pages: int = 0
    
    @property
    def used_pages(self) -> int:
        """已使用的页数"""
        return self.total_pages - self.free_pages
    
    @property
    def page_utilization(self) -> float:
        """页利用率"""
        if self.total_pages == 0:
            return 0.0
        return self.used_pages / self.total_pages
    
    def record_allocation(self):
        """记录页分配"""
        self.pages_allocated += 1
        self.free_pages -= 1
    
    def record_deallocation(self):
        """记录页释放"""
        self.pages_deallocated += 1
        self.free_pages += 1
    
    def record_read(self):
        """记录页读取"""
        self.pages_read += 1
    
    def record_write(self):
        """记录页写入"""
        self.pages_written += 1
    
    def record_disk_read(self):
        """记录磁盘读取"""
        self.disk_reads += 1
    
    def record_disk_write(self):
        """记录磁盘写入"""
        self.disk_writes += 1
    
    def __str__(self) -> str:
        return (f"StorageStats(allocated={self.pages_allocated}, "
                f"used={self.used_pages}/{self.total_pages}, "
                f"utilization={self.page_utilization:.2%})")


@dataclass
class LogEntry:
    """日志条目"""
    timestamp: datetime
    level: str
    operation: str
    page_id: int
    details: str = ""
    
    def __str__(self) -> str:
        time_str = self.timestamp.strftime("%H:%M:%S.%f")[:-3]
        return f"[{time_str}] {self.level:5} {self.operation:12} page_id={self.page_id:4} {self.details}"


class Logger:
    """存储系统日志记录器"""
    
    def __init__(self, max_entries: int = 1000):
        self.max_entries = max_entries
        self.entries: List[LogEntry] = []
        self.enabled = True
    
    def log(self, level: str, operation: str, page_id: int, details: str = ""):
        """记录日志"""
        if not self.enabled:
            return
            
        entry = LogEntry(
            timestamp=datetime.now(),
            level=level,
            operation=operation,
            page_id=page_id,
            details=details
        )
        
        self.entries.append(entry)
        
        # 保持日志条目数量在限制内
        if len(self.entries) > self.max_entries:
            self.entries = self.entries[-self.max_entries:]
    
    def info(self, operation: str, page_id: int, details: str = ""):
        """记录信息级别日志"""
        self.log("INFO", operation, page_id, details)
    
    def warn(self, operation: str, page_id: int, details: str = ""):
        """记录警告级别日志"""
        self.log("WARN", operation, page_id, details)
    
    def error(self, operation: str, page_id: int, details: str = ""):
        """记录错误级别日志"""
        self.log("ERROR", operation, page_id, details)
    
    def get_recent_logs(self, count: int = 50) -> List[LogEntry]:
        """获取最近的日志条目"""
        return self.entries[-count:] if count < len(self.entries) else self.entries
    
    def clear_logs(self):
        """清空日志"""
        self.entries.clear()
    
    def enable_logging(self):
        """启用日志记录"""
        self.enabled = True
    
    def disable_logging(self):
        """禁用日志记录"""
        self.enabled = False
    
    def print_recent_logs(self, count: int = 20):
        """打印最近的日志"""
        recent_logs = self.get_recent_logs(count)
        print(f"\n=== 最近 {len(recent_logs)} 条日志 ===")
        for entry in recent_logs:
            print(entry)
        print("=" * 50)
